package com.alan.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@RestController
public class TestController {

    @SentinelResource(value = "sayHello")
    @RequestMapping(value = "test/hello")
    public String sayHello(String a){
        return "hello" + a;
    }

    public static void main(String[] args) {
        initFlowRules();
        int size = 1;
        CountDownLatch countDownLatch = new CountDownLatch( size );
        for (int i=0; i< size ; i++) {
            Thread thread = new Thread(()->{
                for (int j = 0; j < 10; j++){
//                    try {
//                        Thread.sleep(100);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    TestController.sayHello(j);
                }
            });
            thread.setName("线程-" + (i+1));
            thread.start();
            countDownLatch.countDown();
        }

    }

    public static String sayHello(Integer num){
        Entry entry = null;
        String str = "";
        try {
            entry = SphU.entry("sayHello");
            /*您的业务逻辑 - 开始*/
            str = Thread.currentThread().getName() + ": hello world num : " + num;
            System.out.println( str );
            /*您的业务逻辑 - 结束*/
        } catch (BlockException e1) {
            /*流控逻辑处理 - 开始*/
            str = Thread.currentThread().getName() + ": block! num : " + num;
            System.err.println( str );
            /*流控逻辑处理 - 结束*/
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return str;
    }

    public static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("sayHello");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

}
